<template>
    <div>
        <el-card class="reservation-card">
            <div class="header-container">
                <span class="header-title">就诊列表</span>
            </div>
            <el-table :data="users" style="width: 100%" border>
                <el-table-column label="ID" prop="id"></el-table-column>
                <el-table-column label="姓名" prop="name"></el-table-column>
                <el-table-column label="医生" prop="doctor"></el-table-column>
                <el-table-column label="时间" prop="reservationTime"></el-table-column>
                <el-table-column label="科室" prop="department"></el-table-column>
                <el-table-column label="状态" prop="state">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.state === '1' ? 'warning' : 'success'">
                            {{ scope.row.state === '1' ? '预约中' : '已就诊' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                        <el-button type="text" @click="openDiagnosisDrawer(scope.row)">{{ scope.row.state==="1"? "诊断":disabled}}</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- Diagnosis Drawer -->
        <el-drawer :visible="diagnosisDrawerVisible" title="诊断步骤" @close="closeDiagnosisDrawer">
            <el-card class="checked-card">

                <!-- Step 1: Patient Information -->
                <el-collapse v-model="activeStep" @change="handleStepChange">
                    <el-collapse-item :title="`步骤 1: 基本信息`" name="1">
                        <el-form :model="patientInfoForm" label-width="80px">
                            <el-form-item label="姓名">
                                <el-input v-model="patientInfoForm.name" :disabled="isStepDisabled(1)"></el-input>
                            </el-form-item>
                            <el-form-item label="科室">
                                <el-input v-model="patientInfoForm.department" :disabled="isStepDisabled(1)"></el-input>
                            </el-form-item>
                            <el-form-item label="时间">
                                <el-input v-model="patientInfoForm.time" :disabled="isStepDisabled(1)"></el-input>
                            </el-form-item>
                            <el-form-item label="病例">
                                <el-input v-model="patientInfoForm.cases" type="textarea"
                                    :disabled="isStepDisabled(1)"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-collapse-item>

                    <!-- Step 2: Examination -->
                    <el-collapse-item :title="`步骤 2: 检查项目`" name="2">
                        <div>
                            <el-select v-model="patientInfoForm.selectedExamination" placeholder="选择检查项目"
                                @change="handleExaminationChange">
                                <el-option v-for="option in  examinationList" :key="option.id" :label="option.name"
                                    :value="option.name">
                                </el-option>
                            </el-select>
                            <div>
                                <strong>检查价格: </strong> {{ patientInfoForm.examinationprice }}
                            </div>
                        </div>
                    </el-collapse-item>

                    <!-- Step 3: Prescription -->
                    <el-collapse-item :title="`步骤 3: 处方药`" name="3">
                        <div>
                            <el-select v-model="patientInfoForm.selectedMedication" placeholder="选择处方药"
                                @change="handleMedicationChange(option)">
                                <el-option v-for="option in  medicationList" :key="option.id" :label="option.name"
                                    :value="option.name">
                                </el-option>
                            </el-select>
                            <div>
                                <strong>药物价格: </strong> {{ patientInfoForm.medicationprice }}
                            </div>
                        </div>
                    </el-collapse-item>
                </el-collapse>

                <!-- Step 4: Submit Invoice -->
                <el-button type="primary" @click="submitInvoice" :disabled="isStepDisabled(4)">提交缴费单</el-button>
            </el-card>
        </el-drawer>
    </div>
</template>
  
<script>
import axios from 'axios';

export default {

    data() {
        return {
            users: [],
            name: '',
            diagnosisDrawerVisible: false,
            selectedUser: null,
            activeStep: '1',
            patientInfoForm: {
                name: '',
                department: '',
                time: '',
                cases: '',
                selectedExamination: '',
                examinationprice: 0,
                selectedMedication: '',
                medicationprice: 0,
                total: 0,
                doctor:''
            },
            examinationList: [
            ],
            medicationList: [
            ],
        };
    },
    mounted() {
        this.name=this.$store.state.user.name
        this.getlist()
        this.getmedication()
        this.getExamination()
      

    },
    computed: {
        total() {
            // Sum up examinationprice and medicationprice
            return this.patientInfoForm.examinationprice + this.patientInfoForm.medicationprice;
        },
        user() {
      return this.$store.state.user.name;
    },
    },
    watch: {
        'patientInfoForm.selectedMedication': function (newMedication) {
            // Assuming you have a property 'price' in your medicationList
            const selectedMedication = this.medicationList.find(medication => medication.name === newMedication);
            if (selectedMedication) {
                this.patientInfoForm.medicationprice = selectedMedication.price || 0;
                this.updateTotal();
            }
        },
        'patientInfoForm.selectedExamination': function (newExamination) {
            // Assuming you have a property 'price' in your examinationList
            const selectedExamination = this.examinationList.find(examination => examination.name === newExamination);
            if (selectedExamination) {
                this.patientInfoForm.examinationprice = selectedExamination.price || 0;
                this.updateTotal();
            }
        },
    },
    methods: {
        handleExaminationCommand(command) {

        },
        handleMedicationCommand(command) {
            console.log(command);
        },
        getlist() {
            axios.get(`http://127.0.0.1:3000/api/addreser/doctor/${this.name}`)
                .then(response => {
                    this.users = response.data;
                })
                .catch(error => {
                    console.error('Error fetching users:', error);
                    this.$message.error('获取用户列表时发生错误');
                })
        },
        decreaseMedicationNumber(name) {
      // Send a POST request to decrease the 'number' column for the specified 'name'
      axios.post('http://127.0.0.1:3000/api/decrease-medication', { name })
        .then(response => {
          console.log(response.data); // Log the response from the server
          // Handle success, if needed
        })
        .catch(error => {
          console.error('Error decreasing medication number:', error);
          // Handle error, if needed
        });
    },
        getmedication() {
            // 发送 GET 请求获取所有药物信息
            axios.get('http://127.0.0.1:3000/api/medications')
                .then(response => {
                    // 请求成功处理
                    console.log('药物信息:', response.data);
                    this.medicationList = response.data
                })
                .catch(error => {
                    // 请求失败处理
                    console.error('获取药物信息时发生错误:', error);
                });
        },
        getExamination() {
            axios.get('http://127.0.0.1:3000/api/examination')
                .then(response => {
                    // Handle successful response
                    this.examinationList = response.data;
                })
                .catch(error => {
                    // Handle error
                    console.error('Error fetching examination data:', error);
                });
        },

        openDiagnosisDrawer(user) {
            this.selectedUser = user;
            this.patientInfoForm.doctor=user.doctor
            console.log(this.selectedUser);
            this.diagnosisDrawerVisible = true;
            this.populatePatientInfoForm();
            this.changestate(user.id)
        },
        closeDiagnosisDrawer() {
            this.selectedUser = null;
            this.diagnosisDrawerVisible = false;
            // Clear form data if needed
            this.clearFormData();
        },
        populatePatientInfoForm() {
            // Populate patientInfoForm with data received from selectedUser
            this.patientInfoForm.name = this.selectedUser.name || '';
            this.patientInfoForm.department = this.selectedUser.department || '';
            this.patientInfoForm.time = this.selectedUser.reservationTime || '';
            // ... other assignments ...
        },
        clearFormData() {
            // Clear form data if needed
            this.patientInfoForm.name = '';
            this.patientInfoForm.age = '';
            this.patientInfoForm.time = '';
            this.patientInfoForm.case = '';
            this.examinationList = [];
            this.medicationList = [];
            this.activeStep = '1';
        },
        handleStepChange(val) {
            // Do something when the active step changes
        },
        isStepDisabled(step) {
            // You can implement logic to disable a step based on conditions
            // For simplicity, we assume all steps are always enabled
            return false;
        },
        updateTotal() {
            // Update total based on examinationprice and medicationprice
            const examinationPrice = parseInt(this.patientInfoForm.examinationprice);
            const medicationPrice = parseInt(this.patientInfoForm.medicationprice);
            this.patientInfoForm.total = isNaN(examinationPrice) || isNaN(medicationPrice) ? 0 : examinationPrice + medicationPrice;
        },
        submitInvoice() {
            const data = {
                department: this.patientInfoForm.department,
                time: this.patientInfoForm.time,
                cases: this.patientInfoForm.cases,
                examination: this.patientInfoForm.selectedExamination,
                medication: this.patientInfoForm.selectedMedication,
                examinationprice: this.patientInfoForm.examinationprice,  // Replace with your actual examination price
                medicationprice: this.patientInfoForm.medicationprice,   // Replace with your actual medication price
                total: this.patientInfoForm.total,
                name:this.patientInfoForm.name,
                doctor:this.patientInfoForm.doctor            // Replace with your actual total value
            };
            this.decreaseMedicationNumber(data.medication);
            
            axios.post('http://127.0.0.1:3000/api/pay', data)
                .then(response => {
                    console.log('Response from server:', response.data);
                    this.diagnosisDrawerVisible = false;
                    
                    this.$message.success('就诊完成');
                })
                .catch(error => {
                    console.error('Error sending POST request:', error);
                });
        },
        changestate(id){
            axios.put(`http://127.0.0.1:3000/api/update-user-state/${id}`)
        .then(response => {
            // Handle the response data
            console.log(response.data);
        })
        .catch(error => {
            // Handle errors
            console.error('An error occurred while making the Axios PUT request:', error);
        });
        }
    },
};
</script>
  
<style scoped>
.reservation-card {
    margin-bottom: 20px;
}

.checked-card {
    margin-bottom: 20px;
}

.header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.header-title {
    font-size: 18px;
    font-weight: bold;
}
</style>
  